package com.woniuxy.shiro;

import com.woniuxy.ResponseResult;
import com.woniuxy.jwt.Audience;
import com.woniuxy.jwt.JwtUtil;
import com.woniuxy.service.UseUserService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * 使用jwt来验证用户是否登录
 */
public class JwtRealm extends AuthorizingRealm {
    @Autowired
    private Audience audience;

//    @Autowired
//    private UseUserService useUserService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        String jwt = principalCollection.getPrimaryPrincipal().toString();
        String account = JwtUtil.getAccount(jwt,audience.getBase64Secret());
        //ResponseResult users = useUserService.getUsers(account);
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
//        if (users!=null){
//            info.addRole("user");
//        }
        return null;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        JwtToken jwtToken = (JwtToken)authenticationToken;
        if (jwtToken.getPrincipal()==null){
            throw new AuthenticationException("没有登录");
        }
        String jwt = jwtToken.getPrincipal().toString();
        if (!JwtUtil.parseJwt(jwt,audience.getBase64Secret())){
            throw new AuthenticationException("校验jwt异常");
        }

        String account = JwtUtil.getAccount(jwt,audience.getBase64Secret());
//        ResponseResult users = useUserService.getUsers(account);
//        if (users.getCode()!=200){
//            throw new AuthenticationException("用户不存在");
//        }

        return new SimpleAuthenticationInfo(jwt,jwt,getName());
    }

    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JwtToken;
    }
}
